import router from './router'
import store from './store'
import { Message } from 'element-ui'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
import { getAccessToken } from '@/utils/auth'
import { isRelogin } from '@/utils/request'
import { getOneBIstr } from '@/api/custom/message'
import { getHomePage } from '@/api/login'
import { getQiankunEnv, getCurrentMicroApp, getExchangePortalTitle, getExchangePortalLogo } from '@/utils/micro'
import { MicroAppNameEnum } from '@/utils/constants'
import { isExchangeJuyeDeployMode } from '@/utils/deploy/mode'
import { exchangeJuyeUnifyPortalPath } from '@/utils/deploy/utils'
NProgress.configure({ showSpinner: false })

// 增加三方登陆 update by awesome
const whiteList = ['/login', '/social-login', '/auth-redirect', '/bind', '/register', '/auto-login']

// 共享交换-巨野版本，添加门户白名单
if (isExchangeJuyeDeployMode) {
  whiteList.push(`/${exchangeJuyeUnifyPortalPath}`)
}

router.beforeEach((to, from, next) => {
  if (to.query.mobileAppid) { // 移动端分享转发
    const mobileAppid = to.query.mobileAppid
    if (to.query.mobileType === 'mobileType') {
      window.localStorage.clear()
      if (to.query.mobileTurn) {
        window.localStorage.setItem('mobileTurn', decodeURIComponent(to.query.mobileTurn))
      }
      window.localStorage.setItem('mobileAppid', mobileAppid)
    }
  }
  NProgress.start()
  if (getAccessToken()) {
    to.meta.title && store.dispatch('settings/setTitle', to.meta.title)
    /* has token*/
    // if(to.path === '/signInPage'){ // 跳转到OneBI
    //     getOneBIstr().then((res) => {
    //       if(res.code === 0){
    //         window.location.href = res.data
    //       }
    //     })
    // }
    if (to.path === '/login' || to.path === '/') {
      getHomePage().then(res => {
        next({ path: res.data.path })
      }).catch(error => {
        localStorage.clear()
        console.log(error)
      })
      // next({ path: '/' })
    } else {
      // 获取表单名称，在页标签上显示
      if (to.params.formName) {
        to.meta.title = to.params.formName
      }
      // 获取门户名称，在页标签上显示
      if (to.params.portalName) {
        to.meta.title = to.params.portalName
      }
      if (store.getters.roles.length === 0) {
        isRelogin.show = true
        // 获取字典数据 add by awesome
        store.dispatch('dict/loadDictDatas')
        // 判断当前用户是否已拉取完user_info信息
        store.dispatch('GetInfo').then(() => {
          isRelogin.show = false
          store.dispatch('GenerateRoutes').then(accessRoutes => {
            // 根据roles权限生成可访问的路由表
            router.addRoutes(accessRoutes) // 动态添加可访问路由表
            next({ ...to, replace: true }) // hack方法 确保addRoutes已完成
          })
        }).catch(err => {
          store.dispatch('LogOut').then(() => {
            Message.error(err)
            // next({ path: '/' })
            getHomePage().then(res => {
              next({ path: res.data.path })
            }).catch(error => {
              console.log(error)
            })
          })
        })
        store.dispatch('GetLoginConf').then(() => {})
      } else {
        if (!getQiankunEnv()) {
          next()
        } else {
          // 已在菜单管理中注册的菜单，没有匹配，则跳转到404页面
          if (!to.matched || to.matched.length === 0) {
            next('/404')
          } else {
            next()
          }
        }
      }
      document.title = store.state.user.loginConfigData.loginName
    }
  } else {
    if (!getQiankunEnv()) {
      // 没有token
      if (whiteList.indexOf(to.path) !== -1) {
        // 在免登录白名单，直接进入
        next()
      } else {
        next(`/login?redirect=${to.fullPath}`) // 否则全部重定向到登录页
      }
    } else {
      /* qiankun微前端，过滤子应用白名单 */
      const dataSharePortalPrefix = MicroAppNameEnum.DATA_SHARE_PORTAL.name; // 门户子应用前缀
      // 子应用白名单列表
      const microAppWhiteList = [
        `/${dataSharePortalPrefix}/homePage`,
        `/${dataSharePortalPrefix}/resource-catalog/list`,
        `/${dataSharePortalPrefix}/resource/list`,
        `/${dataSharePortalPrefix}/resource-catalog/detail`,
        `/${dataSharePortalPrefix}/resource/detail`,
        `/${dataSharePortalPrefix}/policy/list`,
        `/${dataSharePortalPrefix}/policy/details`,
        // `/${dataSharePortalPrefix}/unifyPortal`,
      ];
      // 是否在微应用白名单
      const isInMicroAppWhitelist = microAppWhiteList.some((item) =>
          to.path?.toLowerCase()?.startsWith(item.toLowerCase())
        );
      if (isInMicroAppWhitelist) {
        next();
      } else {
        // 没有token
        if (whiteList.indexOf(to.path) !== -1) {
          // 在免登录白名单，直接进入
          next()
        } else {
          next(`/login?redirect=${to.fullPath}`) // 否则全部重定向到登录页
        }
      }
    }
  }
  // qiankun微前端，手动设置子应用的浏览器标题和logo
  if (getQiankunEnv()) {
    setMicroAppBrowserTitleAndLogo(to)
  }
  // NProgress.done()
})
router.afterEach(() => {
  NProgress.done()
})

/**
 * qiankun微前端，手动设置子应用的浏览器标题和logo
 * @param {*} to
 */
const setMicroAppBrowserTitleAndLogo = (to) => {
  const currentMicroApp = getCurrentMicroApp(to.path)
  if (currentMicroApp) {
    /* 设置子应用浏览器标题和logo */
    // 针对共享交换门户，单独动态设置浏览器标题
    if (currentMicroApp.name === MicroAppNameEnum.DATA_SHARE_PORTAL.name) {
      getExchangePortalTitle().then((value) => {
        if (value) {
          document.title = value
        }
      })
    } else {
      // 由于App.vue中metaInfo会设置标题，保险起见，这块设置为异步逻辑
      setTimeout(() => {
        // 浏览器标题
        document.title = currentMicroApp.desc
      }, 0);
    }
    // 浏览器logo
    const link = document.querySelector("link[rel*='icon']") || document.createElement('link')
    link.type = 'image/x-icon'
    link.rel = 'shortcut icon'
    // 针对共享交换门户，单独动态设置浏览器logo
    if (currentMicroApp.name === MicroAppNameEnum.DATA_SHARE_PORTAL.name) {
      getExchangePortalLogo().then((value) => {
        if (value) {
          link.href = value
          document.getElementsByTagName('head')[0].appendChild(link)
        }
      })
    } else {
      link.href = require(`@/assets/images/${currentMicroApp.log}`)
      document.getElementsByTagName('head')[0].appendChild(link)
    }
  } else {
    // 共享交换-巨野版本，设置浏览器标题
    setTimeout(() => {
      if (
        isExchangeJuyeDeployMode &&
        (to.path?.toLowerCase().startsWith(`/${exchangeJuyeUnifyPortalPath}`) ||
          window.location.pathname
            .toLowerCase()
            .startsWith(process.env.VUE_APP_APP_NAME + exchangeJuyeUnifyPortalPath))
      ) {
        document.title = "巨野县一体化大数据平台";
      }
    }, 0)
    // 系统管理，设置系统默认的浏览器logo
    const link = document.querySelector("link[rel*='icon']") || document.createElement('link')
    link.type = 'image/x-icon'
    link.rel = 'shortcut icon'
    link.href = store?.state?.user?.loginConfigData?.browserUrl
    document.getElementsByTagName('head')[0].appendChild(link)
  }
}
